package com.flower8.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.flower8.model.Agent;
import com.flower8.model.AgentExport;
import com.flower8.model.ExportData;
import com.flower8.service.AgentService;
import com.flower8.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 渠道商控制层
 * @Author: tanglin
 * @Date: 2020/5/21 15:05
 * @Version: 1.0
 */
@RestController
@RequestMapping("/agent")
public class AgentController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(AgentController.class);

    @Autowired
    private AgentService agentService;


    /**
     * 查询渠道商列表
     * @param request
     * @return
     */
    @RequestMapping("/getAgentList")
    public Object getBankData(HttpServletRequest request){
        logBefore(log, "++++++++++ 查询渠道商列表 ++++++++++");
        PageData pd = new PageData(request);

        pd.put("start", Integer.parseInt( pd.get("start").toString() ) );
        pd.put("length", Integer.parseInt( pd.get("length").toString() ) );

        Map res = new HashMap();
        try {
            List<Map> data =  agentService.getAgentList(pd);
            int total = agentService.getAgentListCount(pd);
            res.put("data", data);
            res.put("recordsTotal", total);   //dataTable分页需要
            res.put("recordsFiltered", total);//dataTable分页需要
            res.put("draw", pd.get("draw").toString());//dataTable分页需要
            logAfter(log);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return res;
    }

    /**
     * 根据账号id查询
     * @param id 账号id
     * @return
     */
    @RequestMapping("/getAgentById")
    public Object getAgentById(@RequestParam Long id){
        logBefore(log, "++++++++++ 根据账号id查询 ++++++++++");
        Agent agent = null;
        try {
            agent = agentService.getById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logAfter(log);
        return agent;
    }

    /**
     * 根据账号查询
     * @param account 登录账号
     * @return
     */
    @RequestMapping("/getAgentByAccount")
    public Object getAgentByAccount(@RequestParam String account){
        logBefore(log, "++++++++++ 根据账号查询 ++++++++++");

        Map res = new HashMap();
        try {
            Agent agent = agentService.getUser(account);
            res.put("data",agent);
            return res;
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * 新增渠道商
     * @param request
     * @return
     */
    @RequestMapping("/addAgent")
    public Object addAgent(HttpServletRequest request){
        logBefore(log, "++++++++++ 新增渠道商 ++++++++++");
        PageData pd = new PageData(request);

        Map res = new HashMap();
        try {
            String code = AgentUtils.createAgentCode();
            pd.put("code",code );
            String newPass = UserUtil.addPass(pd.getString("password"), code);
            pd.put("password", newPass);
            agentService.addAgent(pd);
            res.put("msg","操作成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            res.put("msg","操作失败");
        }
        return res;
    }

    /**
     * 重置密码
     * @param request
     * @return
     */
    @RequestMapping("/restPwd")
    public Object restPwd(HttpServletRequest request){
        logBefore(log, "++++++++++ 重置密码 ++++++++++");
        PageData pd = new PageData(request);

        Map res = new HashMap();
        try {
            Agent agent = agentService.getById(Long.parseLong(pd.getString("id")));
            String newPass = UserUtil.addPass(pd.getString("password"), agent.getCode());
            pd.put("password", newPass);
            agentService.updateAgentInfo(pd);
            res.put("msg","操作成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            res.put("msg","操作失败");
        }
        return res;
    }

    /**
     * 修改渠道商信息
     * @param request
     * @return
     */
    @RequestMapping("/updateAgentInfo")
    public Object updateAgentInfo(HttpServletRequest request){
        logBefore(log, "++++++++++ 修改渠道商信息 ++++++++++");
        PageData pd = new PageData(request);

        Map res = new HashMap();
        try {
            agentService.updateAgentInfo(pd);
            res.put("msg","操作成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            res.put("msg","操作失败");
        }
        return res;
    }

    /**
     * 删除渠道商信息
     * @param id
     * @return
     */
    @RequestMapping("/deleteAgent")
    public Object deleteAgent(@RequestParam Long id){
        logBefore(log, "++++++++++删除渠道商信息 ++++++++++");

        Map res = new HashMap();
        try {
            agentService.deleteAgent(id);
            res.put("msg","操作成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            res.put("msg","操作失败");
        }
        return res;
    }


    /**
     * 查询渠道号列表
     * @param request
     * @return
     */
    @RequestMapping("/getAgentChannelList")
    public Object getAgentChannelList(HttpServletRequest request){
        logBefore(log, "++++++++++ 查询渠道号列表 ++++++++++");
        PageData pd = new PageData(request);

        pd.put("start", Integer.parseInt( pd.get("start").toString() ) );
        pd.put("length", Integer.parseInt( pd.get("length").toString() ) );

        Map res = new HashMap();
        try {
            List<Map> data =  agentService.getAgentChannelList(pd);
            int total = agentService.getAgentChannelCount(pd);
            res.put("data", data);
            res.put("recordsTotal", total);   //dataTable分页需要
            res.put("recordsFiltered", total);//dataTable分页需要
            res.put("draw", pd.get("draw").toString());//dataTable分页需要
            logAfter(log);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return res;
    }

    /**
     * 查询所有渠道商
     * @return
     */
    @RequestMapping("/getAllAgent")
    public Object getAllAgent(){
        logBefore(log, "++++++++++查询所有渠道商 ++++++++++");

        Map res = new HashMap();
        try {
            List<Agent> agent = agentService.getAllAgent();
            res.put("data", agent);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return res;
    }


    /**
     * 新增渠道号
     * @param request
     * @return
     */
    @RequestMapping("/addAgentChannel")
    public Object addAgentChannel(HttpServletRequest request){
        logBefore(log, "++++++++++新增渠道号 ++++++++++");
        PageData pd = new PageData(request);

        try {
            agentService.addAgentChannel(pd);
            return returnSuccessMsg(null,"新增成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return returnFailureMsg("新增失败");
        }
    }

    /**
     * 删除渠道号
     * @param id
     * @return
     */
    @RequestMapping("/delAgentChannel")
    public Object delAgentChannel(@RequestParam Long id){
        logBefore(log, "++++++++++删除渠道号 ++++++++++");

        try {
            agentService.delAgentChannel(id);
            return returnSuccessMsg(null,"删除成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return returnFailureMsg("删除失败");
        }
    }

    /**
     * 查询推广注册人数统计数据
     * @param request
     * @return
     */
    @RequestMapping("/getStaticTotal")
    public Object getStaticTotal(HttpServletRequest request){
        logBefore(log, "++++++++++ 查询统计数据列表 ++++++++++");
        PageData pd = new PageData(request);

        pd.put("start", Integer.parseInt( pd.get("start").toString() ) );
        pd.put("length", Integer.parseInt( pd.get("length").toString() ) );

        Map res = new HashMap();
        try {

            List<Map> data =  agentService.getStaticTotal(pd);
            int total = agentService.getStaticTotalCount(pd);
            res.put("data", data);
            res.put("recordsTotal", total);   //dataTable分页需要
            res.put("recordsFiltered", total);//dataTable分页需要
            res.put("draw", pd.get("draw").toString());//dataTable分页需要
            logAfter(log);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return res;
    }

    /**
     * 导出数据
     * @param request
     * @param response
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response){
        logBefore(log, "++++++++++ 导出数据 ++++++++++");
        PageData pd = new PageData(request);
        try {
            List<ExportData> dataList =agentService.exportData(pd);
            if(CollectionUtils.isEmpty(dataList)){
                throw new Exception("暂无数据，导出失败");
            }


            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            String fileName = URLEncoder.encode(  "用户注册数据统计", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExportData.class).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("数据统计页").doWrite(dataList);
            logAfter(log);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    /**
     * 查询注册用户脱敏数据列表
     * @param request
     * @return
     */
    @RequestMapping("/getDetailList")
    public Object getDetailList(HttpServletRequest request){
        logBefore(log, "++++++++++ 查询注册用户脱敏数据列表 ++++++++++");
        PageData pd = new PageData(request);

        pd.put("start", Integer.parseInt( pd.get("start").toString() ) );
        pd.put("length", Integer.parseInt( pd.get("length").toString() ) );

        Map res = new HashMap();
        try {
            List<Map> data =  agentService.getDetailList(pd);
            int total = agentService.getDetailListCount(pd);
            res.put("data", data);
            res.put("recordsTotal", total);   //dataTable分页需要
            res.put("recordsFiltered", total);//dataTable分页需要
            res.put("draw", pd.get("draw").toString());//dataTable分页需要
            logAfter(log);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return res;
    }

    /**
     * 导出注册用户脱敏数据列表
     * @param request
     * @return
     */
    @RequestMapping("/exportRegisterData")
    public void exportRegisterData(HttpServletRequest request, HttpServletResponse response){
        logBefore(log, "++++++++++ 导出注册用户脱敏数据列表 ++++++++++");
        PageData pd = new PageData(request);
        try {
            List<AgentExport> dataList =agentService.exportRegisterData(pd);
            if(CollectionUtils.isEmpty(dataList)){
                throw new Exception("暂无数据，导出失败");
            }

            for (AgentExport AgentExport : dataList) {
                if(AgentExport.getStatus() != null ){
                    if("1".equals(AgentExport.getStatus())){
                        AgentExport.setStatus( "是");
                    }else{
                        AgentExport.setStatus( "否");
                    }
                }
                //名字脱敏处理
                if(!"".equals(AgentExport.getUserName())){
                    AgentExport.setUserName(UserUtil.changeUserName(AgentExport.getUserName()));
                }
                //手机号脱敏处理
                if(!"".equals(AgentExport.getMobile())){
                    AgentExport.setMobile(UserUtil.changeMobile(AgentExport.getMobile()));
                }
            }

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            String fileName = URLEncoder.encode(  "脱敏数据导出", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), AgentExport.class).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("数据统计页").doWrite(dataList);
            logAfter(log);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    /**
     * 查询中注册数和实名数
     * @return
     */
    @RequestMapping("/getTotal")
    public Object getTotal(@RequestParam(required = false) Long agentId){
        logBefore(log, "++++++++++ 查询中注册数和实名数 ++++++++++");
        try {
            Map data = agentService.getTotal(agentId);
            logAfter(log);
            return data;
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return null;
        }
    }
}
